package jwei.apps.zappos;

import java.util.ArrayList;
import java.util.List;

import jwei.apps.helpers.ConnectionManager;
import jwei.apps.helpers.GetMethods;
import jwei.apps.objects.APIConstants;

import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class ZapposAutocomplete {

    private static DefaultHttpClient httpClient = ConnectionManager.getClient();

    public static List<String> searchTerm(String term) {
        term = term.replace(" ", "%20");
        String url = String.format(APIConstants.AUTOCOMPLETE, term);
        String response = GetMethods.doGetWithResponse(url, httpClient);
        if (!response.equals("")) {
            try {
                JSONObject jsonResponse = new JSONObject(response);
                JSONArray results = jsonResponse.getJSONArray("results");
                // list or array? is one significantly faster than the other?
                List<String> ret = new ArrayList<String>();
                for (int i = 0; i < results.length(); i++) {
                    ret.add(results.getString(i));
                }
                return ret;
            } catch (JSONException e) {
                e.printStackTrace();
                return null;
            }
        } else {
            System.out.println(ZapposAutocomplete.class.getCanonicalName() + ": Did not retrieve response");
            return null;
        }
    }

}
